package com.example.goods_admin.service.impl;

import com.example.goods_admin.common.Result;
import com.example.goods_admin.entity.Goods;
import com.example.goods_admin.entity.GoodsImg;
import com.example.goods_admin.mapper.UploadFileMapper;
import com.example.goods_admin.service.UploadFileService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.*;
import java.util.*;

@Service
public class UploadFileServiceImpl implements UploadFileService {
    @Autowired
    UploadFileMapper uploadFileMapper;

    @Override
    public Result uploadImage(MultipartFile[] imageFile, String goodsId) {

        // 指定目标文件夹路径 liunx windows
        String folderPath = "/home/files/";

        // 更新商品信息
        Goods goods=new Goods();
        goods.setId(goodsId);

        try {
            List<GoodsImg> goodsImgList = new ArrayList<>();
            // 遍历上传的文件数组
            for (MultipartFile file : imageFile) {
                //图片的全称，test.png
                String originalFilename = file.getOriginalFilename();

                Path path = Paths.get(originalFilename);
                String fileExtension = getFileExtension(path);

                GoodsImg goodsImg = new GoodsImg();
                String imgId = UUID.randomUUID().toString();

                String alisImgName = imgId + "." + fileExtension;

                // 构建目标文件路径
                Path targetPath = Paths.get(folderPath, alisImgName);

                // 将文件保存到目标文件夹(使用输入输出流上传文件到服务器)
                try (InputStream inputStream = file.getInputStream();
                     FileChannel destinationChannel = FileChannel.open(targetPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
                    destinationChannel.transferFrom(Channels.newChannel(inputStream), 0, Long.MAX_VALUE);
                }

                goodsImg.setImgId(imgId);
                goodsImg.setGoodsId(goodsId);
                goodsImg.setImageName(originalFilename);
                goodsImg.setImageUrl("http://124.220.110.203:8080/api/"+alisImgName);
                goodsImg.setStatus("1");
                goodsImgList.add(goodsImg);
            }


            uploadFileMapper.saveGoodsImg(goodsImgList);

            // 文件保存成功，返回相应信息
            return Result.succeed("文件保存成功！",goodsImgList);
        } catch (IOException e) {
            e.printStackTrace();

            // 文件保存失败，返回错误信息
            return  Result.failed ("文件保存失败！",new HashMap<String,Object>());
        }
    }

    private static String getFileExtension(Path path) {
        String fileName = path.getFileName().toString();
        int lastIndexOfDot = fileName.lastIndexOf(".");
        if (lastIndexOfDot > 0) {
            return fileName.substring(lastIndexOfDot + 1);
        }
        return "";
    }




//    @Override
//    public Result uploadImage(MultipartFile[] imageFile, String id) {
//
//        //1、吧图片放到指定的文件夹下
//        //2、更新数据
//
//
//        try {
//            // 指定目标文件夹路径
//            String folderPath = "D:/imagePath/";
//
//            // 获取文件名
//            String fileName ="";
//
//            // 遍历上传的文件数组
//            for (MultipartFile file : imageFile) {
//                // 获取文件名
//                fileName = file.getOriginalFilename();
//
//                // 构建目标文件路径
//                Path targetPath = Paths.get(folderPath, fileName);
//
//                // 将文件保存到目标文件夹
//                Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
//            }
//            Goods goods=new Goods();
//            goods.setId(id);
//            goods.setImageUrl(folderPath+fileName);
//            uploadFileMapper.updateGoods(goods);
//
//            Map<String, Object> resultMap = new HashMap<>();
//            resultMap.put("name",fileName);
//            resultMap.put("url",folderPath+fileName);
//
//            // 文件保存成功，返回相应信息
//            return Result.succeed("文件保存成功！",resultMap);
//        } catch (Exception e) {
//            e.printStackTrace();
//            // 文件保存失败，返回错误信息
//            return  Result.failed ("文件保存失败！",new HashMap<String,Object>());
//        }
//    }

    @Override
    public Result saveGoods(Goods goods) {
        goods.setStatus("1");
        String id = UUID.randomUUID().toString();
        goods.setId(id);
        int count=uploadFileMapper.saveGoods(goods);
        if (count==1){
            return Result.succeed("保存成功",id);
        }else{
            return Result.failed("保存失败",id);
        }
    }

    @Override
    public Result deleteGoodsImage(Goods goods, String imgId) {

        if (goods.getId()!="" && goods.getId()!=null && imgId!="" && imgId!=null ){
            GoodsImg goodsImg = new GoodsImg();
            goodsImg.setImgId(imgId);
            goodsImg.setGoodsId(goods.getId());
            goodsImg.setStatus("0");
            int count=uploadFileMapper.updateGoodsImg(goodsImg);
            if (count==1){
                return Result.succeed("删除成功");
            }else{
                return Result.failed("删除失败");
            }
        }
        return null;
    }

    @Override
    public Result selectGoods(Goods goods) {


        int pageNum = goods.getPageNum()==0?1:goods.getPageNum();
        int pageSize = goods.getPageSize()==0?10:goods.getPageSize();

        //1、开启分页查询
        PageHelper.startPage(pageNum,pageSize);

        //2、查询结果
        List<Goods> goodsList  = uploadFileMapper.selectGoods(goods);

        //3、封装结果
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goodsList);

        Goods goodsRes =uploadFileMapper.selectGoodsById(goods.getId());

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("imgList",goodsPageInfo);
        resultMap.put("name","");
        resultMap.put("price","");
        if (goodsRes!=null){
            resultMap.put("name",goodsRes.getName());
            resultMap.put("price",goodsRes.getPrice());
        }

        //4、返回
        return Result.succeed("查询成功",resultMap);
    }

    @Override
    public Result deletegoods(Goods goods) {

        //删除：物理删除，逻辑删除

        int count=uploadFileMapper.updateGoods(goods);
        if (count==1){
            return Result.succeed("删除成功");
        }else{
            return Result.failed("删除失败");
        }

    }

    @Override
    public Result editGoods(Goods goods) {
        int count=uploadFileMapper.updateGoods(goods);
        if (count==1){
            return Result.succeed("修改成功");
        }else{
            return Result.failed("修改失败");
        }
    }

    @Override
    public Result selectGoodsList(Goods goods) {
        int pageNum = goods.getPageNum()==0?1:goods.getPageNum();
        int pageSize = goods.getPageSize()==0?10:goods.getPageSize();

        //1、开启分页查询
        PageHelper.startPage(pageNum,pageSize);

        //2、查询结果
        List<Goods> goodsList  = uploadFileMapper.selectGoodsList(goods);

        //3、封装结果
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goodsList);

        //4、返回
        return Result.succeed("查询成功",goodsPageInfo);
    }


}
